<template>
  <div class="ebook-reader">
    <div id="read"></div>
    <!-- 蒙板 -->
    <div
      class="ebook-reader-mask"
      @click="onMaskClick"
      @touchmove="move"
      @touchend="moveEnd"
      @mousedown.left="onMouseEnter"
      @mousemove.left="onMouseMove"
      @mouseup.left="onMouseEnd"
    ></div>
    {{ $route.params.fileName }}
  </div>
</template>

<script>
import { flatten } from '@/utils/book';
import { getLocalForage } from '@/utils/localForage';
import {
  getFontFamily,
  getFontSize,
  getLocation,
  getTheme,
  saveFontFamily,
  saveFontSize,
  saveTheme,
} from '@/utils/localStorage';
import { ebookMixin } from '@/utils/mixin.js';
import Epub from 'epubjs';

export default {
  mixins: [ebookMixin],
  methods: {
    // ! 1 鼠标进入
    onMouseEnter(e) {
      this.mouseState = 1;
      this.mouseStartTime = e.timeStamp;
      e.preventDefault();
      e.stopPropagation();
    },
    // ! 2 鼠标进入后的移动
    onMouseMove(e) {
      if (this.mouseState === 1) {
        this.mouseState = 2;
      } else if (this.mouseState === 2) {
        let offsetY = 0;
        if (this.firstOffsetY) {
          offsetY = e.clientY - this.firstOffsetY;
          this.setOffsetY(offsetY);
        } else {
          this.firstOffsetY = e.clientY;
        }
      }
      e.preventDefault();
      e.stopPropagation();
    },
    // ! 3 鼠标从移动状态移出
    // ! 4 鼠标还原状态
    onMouseEnd(e) {
      if (this.mouseState === 2) {
        this.setOffsetY(0);
        this.firstOffsetY = 0;
        this.mouseState = 3;
      } else {
        this.mouseState = 4;
      }
      const time = e.timeStamp - this.mouseStartTime;
      if (time < 200) {
        this.mouseState = 4;
      }
      e.preventDefault();
      e.stopPropagation();
    },
    // *蒙版Y轴偏移函数
    move(e) {
      let offsetY = 0;
      if (this.firstOffsetY) {
        offsetY = e.changedTouches[0].clientY - this.firstOffsetY;
        this.setOffsetY(offsetY);
      } else {
        this.firstOffsetY = e.changedTouches[0].clientY;
      }
      e.preventDefault();
      e.stopPropagation();
    },
    moveEnd() {
      this.setOffsetY(0);
      this.firstOffsetY = 0;
    },
    // *电子书翻页和菜单 显示/隐藏 功能
    onMaskClick(e) {
      if (this.mouseState && (this.mouseState === 2 || this.mouseState === 3)) {
        return;
      }
      const offsetX = e.offsetX;
      const width = window.innerWidth;
      if (offsetX > 0 && offsetX < width * 0.3) {
        this.prevPage();
      } else if (offsetX > 0 && offsetX > width * 0.7) {
        this.nextPage();
      } else {
        this.toggleTitleAndMenu();
      }
    },
    // *翻到上一页
    prevPage() {
      if (this.rendition) {
        this.rendition.prev().then(() => {
          this.refreshLocation();
        });
        this.hideTitleAndMenu();
      }
    },
    // *翻到下一页
    nextPage() {
      if (this.rendition) {
        this.rendition.next().then(() => {
          this.refreshLocation();
        });
        this.hideTitleAndMenu();
      }
    },
    // *通过鼠标点击 [显示/隐藏] 菜单栏
    toggleTitleAndMenu() {
      // 这两行代码等价
      // this.$store.dispatch('setMenuVisible', !this.menuVisible);
      this.setMenuVisible(!this.menuVisible);
      if (this.menuVisible) {
        this.setSettingVisible(-1);
      }
      this.setFontFamilyVisible(false);
    },

    // *初始化字体大小
    initFontSize() {
      let fontSize = getFontSize(this.fileName);
      if (!fontSize) {
        saveFontSize(this.fileName, this.defaultFontSize);
      } else {
        this.rendition.themes.fontSize(fontSize);
        this.setDefaultFontSize(fontSize);
      }
    },
    // *初始化字体族
    initFontFamily() {
      let fontFamily = getFontFamily(this.fileName);
      if (!fontFamily) {
        saveFontFamily(this.fileName, this.defaultFontFamily);
      } else {
        this.rendition.themes.font(fontFamily);
        this.setDefaultFontFamily(fontFamily);
      }
    },
    // *初始化主题
    initTheme() {
      let defaultTheme = getTheme(this.fileName);
      if (!defaultTheme) {
        defaultTheme = this.themeList[0].name;
        saveTheme(this.fileName, defaultTheme);
      }
      this.setDefaultTheme(defaultTheme);
      this.themeList.forEach((theme) => {
        this.rendition.themes.register(theme.name, theme.style);
      });
      this.rendition.themes.select(defaultTheme);
    },

    // *初始化渲染
    initRendition() {
      this.rendition = this.book.renderTo('read', {
        width: innerWidth,
        height: innerHeight,
        method: 'default',
        // flow: 'scrolled',
      });

      // #当前阅读进度
      const location = getLocation(this.fileName);

      if (location) {
        this.rendition.display(location).then(() => {
          this.initTheme();
          this.initFontSize();
          this.initFontFamily();
          this.initGlobalStyle();
          this.refreshLocation();
        });
      } else {
        // #渲染电子书,初始化字体族,存储字体大小
        this.rendition.display().then(() => {
          this.initTheme();
          this.initFontSize();
          this.initFontFamily();
          this.initGlobalStyle();
          this.refreshLocation();
        });
      }

      // #阅读器渲染完后调用
      this.rendition.hooks.content.register((contents) => {
        Promise.all([
          contents.addStylesheet(
            `${process.env.VUE_APP_RES_URL}/fonts/cabin.css`
          ),
          contents.addStylesheet(
            `${process.env.VUE_APP_RES_URL}/fonts/daysOne.css`
          ),
          contents.addStylesheet(
            `${process.env.VUE_APP_RES_URL}/fonts/montserrat.css `
          ),
          contents.addStylesheet(
            `${process.env.VUE_APP_RES_URL}/fonts/tangerine.css`
          ),
        ]);
        // .then(() => {
        //   console.log('字体全部加载完毕');
        // });
      });
    },

    // *初始化手势翻页
    /*     initGesture() {
      this.rendition.on('touchstart', (event) => {
        this.touchStartX = event.changedTouches[0].clientX;
        this.touchStartTime = event.timeStamp;
      });
      this.rendition.on('touchend', (event) => {
        const offsetX = event.changedTouches[0].clientX - this.touchStartX;
        const time = event.timeStamp - this.touchStartTime;
        if (time < 500 && offsetX > 40) {
          this.prevPage();
        } else if (time < 500 && offsetX < -40) {
          this.nextPage();
        } else {
          this.toggleTitleAndMenu();
        }
        event.preventDefault();
        event.stopPropagation();
      });
    }, */

    // *解析电子书
    parseBook() {
      // #获取电子书封面
      this.book.loaded.cover.then((cover) => {
        this.book.archive.createUrl(cover).then((url) => {
          this.setCover(url);
        });
      });
      // #获取标题和作者信息
      this.book.loaded.metadata.then((metadata) => {
        this.setMetadata(metadata);
      });
      // #获取章节信息
      this.book.loaded.navigation.then((nav) => {
        const navItem = flatten(nav.toc);
        function find(item, level = 0) {
          return !item.parent
            ? level
            : find(
                navItem.filter(
                  (parentItem) => parentItem.id === item.parent
                )[0],
                ++level
              );
        }
        navItem.forEach((item) => {
          item.level = find(item);
        });
        this.setNavigation(navItem);
      });
    },
    // *初始化电子书
    initEpub(url) {
      // const url = process.env.VUE_APP_RES_URL + '/' + this.fileName + '.epub';

      this.book = new Epub(url);
      // #vuex变量
      this.setCurrentBook(this.book);

      // #调用初始化渲染函数
      this.initRendition();

      // #启用手势
      // this.initGesture();

      // #调用解析电子书函数
      this.parseBook();

      // #将电子书进行分页
      this.book.ready
        .then(() => {
          return this.book.locations.generate(
            750 * (window.innerWidth / 375) * (getFontSize(this.fileName) / 16)
          );
        })
        .then((locations) => {
          this.navigation.forEach((nav) => {
            nav.pageList = [];
          });
          locations.forEach((item) => {
            const loc = item.match(/\[(.*)\]!/)[1];
            this.navigation.forEach((nav) => {
              if (nav.href) {
                const href = nav.href.match(/^(.*)\.html$/)[1];
                if (href === loc) {
                  nav.pageList.push(item);
                }
              }
            });
            let currentPage = 1;
            this.navigation.forEach((nav, index) => {
              if (index === 0) {
                nav.page = 1;
              } else {
                nav.page = currentPage;
              }
              currentPage += nav.pageList.length + 1;
            });
          });
          this.setPagelist(locations);
          this.setBookAvailable(true);
          this.refreshLocation();
        });
    },
  },
  mounted() {
    // const fileName = this.$route.params.fileName;
    const books = this.$route.params.fileName.split('|');
    const fileName = books[1];
    getLocalForage(fileName, (err, blob) => {
      if (!err && blob) {
        console.log('找到离线缓存电子书');
        this.setFileName(books.join('/')).then(() => {
          this.initEpub(blob);
        });
      } else {
        console.log('在线获取电子书');
        this.setFileName(books.join('/')).then(() => {
          const url =
            process.env.VUE_APP_RES_URL + '/epub/' + this.fileName + '.epub';
          this.initEpub(url);
        });
      }
    });
  },
};
</script>

<style scoped lang="scss">
.ebook-reader {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .ebook-reader-mask {
    position: absolute;
    top: 0;
    left: 0;
    background: transparent;
    z-index: 150;
    width: 100%;
    height: 100%;
  }
}
</style>
